/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package cn.com.digitalnet.ad.security;

import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.utils.Encodes;

import cn.com.digitalnet.ad.entity.Permission;
import cn.com.digitalnet.ad.entity.Role;
import cn.com.digitalnet.ad.entity.User;
import cn.com.digitalnet.ad.exception.CaptchaException;
import cn.com.digitalnet.ad.service.UserService;
import cn.com.digitalnet.ad.web.servlet.CaptchaServlet;

public class ShiroDbRealm extends AuthorizingRealm {
	
	 @Autowired private UserService userService;

	/**
	 * 认证回调函数,登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		if(authcToken instanceof UsernamePasswordCaptchaToken){
			UsernamePasswordCaptchaToken token = (UsernamePasswordCaptchaToken) authcToken;
			///验证码begin
			String captcha = token.getCaptcha();
			String exitCode = (String) SecurityUtils.getSubject().getSession()
					.getAttribute(CaptchaServlet.KEY_CAPTCHA);
			if (null == captcha || !captcha.equalsIgnoreCase(exitCode)) {
				//留一个后门，用于功能测试中绕过验证码校验
				if(!"zidafone".equals(captcha)){
					throw new CaptchaException("验证码错误");
				}
			}
			///验证码end
			
			User user = userService.findUserByLoginName(token.getUsername());
			if (user != null) {
				byte[] salt = Encodes.decodeHex(user.getSalt());
				return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getLoginName(), user.getName()),
						user.getPassword(), ByteSource.Util.bytes(salt), getName());
			} else {
				return null;
			}
		}else{
			return null;
		}
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		User user = userService.findUserByLoginName(shiroUser.loginName);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		List<Role> roles = userService.getRolesForUser(user.getId());
		List<Permission> permissions = userService.getPermissionsForUser(user.getId());
		for (Role role : roles) {
			info.addRole(role.getName());
		}
		for(Permission p : permissions){
			info.addStringPermission(p.getCode());
		}
		return info;
	}

	/**
	 * 设定Password校验的Hash算法与迭代次数.
	 */
	@PostConstruct
	public void initCredentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(UserService.HASH_ALGORITHM);
		matcher.setHashIterations(UserService.HASH_INTERATIONS);

		setCredentialsMatcher(matcher);
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
